'use strict';
/**
 * stock jwt service translate back from their ES6 version.
 * based on https://github.com/auth0/react-flux-jwt-authentication-sample
 */
var request = require('reqwest');
var when = require('when');
var LoginConstants = require('../constants/login');
var LoginActions = require('../actions/login');

var AuthService = function()
{
	this.login = function(username , password)
	{
		// This require a backend that work with jwt authentication
		// you might want to take a look at our panesjs.com framework :)
		return this.handleAuth(when(
			request({
				url: LoginConstants.LOGIN_URL,
				method: 'POST',
				crossOrigin: true,
				type: 'json',
				data: {
					username, password
				}
			})
		));
	};

	this.logout = function()
	{
		LoginActions.logoutUser();
	};

	this.signup = function(username , password , extra)
	{
		return this.handleAuth(when(request({
			url: LoginConstants.SIGNUP_URL,
			method: 'POST',
			crossOrigin: true,
			type: 'json',
			data: {
				username, password, extra
			}
		})));
	};

	this.handleAuth = function(loginPromise)
	{
		return loginPromise
			.then(function(response)
			{
				console.log(response);
				var jwt = response.id_token;
				LoginActions.loginUser(jwt);
				return true;
			});
	};

};

module.exports = new AuthService();
